import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import { ModifyRemindPageService } from "./modify-remind-page.service";
import { AppPaginationComponent, PaginationModel } from "app/widgets/pagination/pagination.component";
import { DetailComponent } from "../../../modal/detail/detail.component";
import { InvestService } from "../../../invest.service";
import { RemindComponent } from "../../../modal/remind/remind.component";
import * as _ from 'lodash';
import { DataService } from 'app/services/data.service';
import { SelectItem } from 'primeng/components/common/api';

@Component({
  selector: 'app-modify-remind-page',
  templateUrl: './modify-remind-page.component.html',
  styleUrls: ['./modify-remind-page.component.scss'],
  providers: [ModifyRemindPageService]
})
export class ModifyRemindPageComponent implements OnInit {
  // 查看明细模版
  @ViewChild("detail", { read: ViewContainerRef })
  detail: ViewContainerRef;
  detailComponent: ComponentRef<DetailComponent>;
  // 提醒者模版
  @ViewChild("modifyTargetRemind", { read: ViewContainerRef })
  modifyTargetRemind: ViewContainerRef;
  remindComponent: ComponentRef<RemindComponent>;

  // lodash
  public _: any = _;
  //短信提醒
  public sSMSFlag: any = false;
  //邮件提醒
  public sEmailFlag: any = false;
  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  // 提醒列表
  public dataList: any;
  // 提醒分页列表post
  public getBody = {
    pageIndex: 1,
    pageSize: 20,
    sOprType: '3',   // 操作类型，投资范围-3
    nBatchno: '',
    sSendFlag: 'N',    // 是否有效，N-否，Y-是，默认传N
    sFundType: '',
    sFundName: '',
    sBeginOperatorZh: '',
    sCommitOperatorZh: '',
    sReceiverZh: '',
    sMsgTitle: ''
  }
  // 列表分页配置
  public listPageInfo = {
    currentPageNum: 1,
    pageSize: 20,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 20, 50, 100]
  }
  // 列表是否全选
  public isCheckedAll = false;
  // 基金状态下拉框值
  public fundStatus: SelectItem[];
  // 提醒信息
  public auditOprZh: any;
  // 提醒信息
  public remindBody: any = {
    auditOpr: '',
    title: '',
    sSMSContent: '',
    sEmailContent: '',
    content: '',
    remark: '',
    sSendFlag: '',
    sButtonId: ''
  };
  // 字典值
  public dictionaryList: any = {
    FUND_TYPE: []
  };

  constructor(
    public modifyRemindPageService: ModifyRemindPageService,
    public resolver: ComponentFactoryResolver,
    public dataService: DataService,
    public investService: InvestService
  ) { }

  ngOnInit() {
    let that = this;
    // 权限处理
    this.dataService.initTree.subscribe((data) => {
      if (data) {
        let SessionMenuData = sessionStorage.getItem('menu');
        this.menuData = JSON.parse(SessionMenuData)
        this.menuResourceSet = [];
        _.forEach(this.menuData, (item, index) => {
          if (item.sName == '风控管理') {
            _.forEach(item.children, (it, idx) => {
              if (it.sName == '投资范围指标') {
                _.forEach(it.children, (ite, i) => {
                  if (ite.sName == '指标修改') {
                    that.menuResourceSet = ite.resourceSet
                    sessionStorage.setItem('btn-rcmi', this.menuResourceSet);
                  }
                })
              }
            })
          }
        })
      }
    })
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData)
    this.menuResourceSet = [];
    _.forEach(this.menuData, (item, index) => {
      if (item.sName == '风控管理') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == '投资范围指标') {
            _.forEach(it.children, (ite, i) => {
              if (ite.sName == '指标修改') {
                that.menuResourceSet = ite.resourceSet
                sessionStorage.setItem('btn-rcmi', this.menuResourceSet);
              }
            })
          }
        })
      }
    })
    // 字典值
    this.dictionaryList = JSON.parse(localStorage.getItem("dictionaryList"));
    this.list();
  }
  ngAfterViewInit() {
    let that = this;
    // 用于接收提醒者数据
    this.investService.remindData = new EventEmitter();
    this.investService.remindData.subscribe((data: any) => {
      if (data) {
        that.remindBody.auditOpr = _.cloneDeep(data.userChecked);
        that.auditOprZh = _.cloneDeep(data.displayName);
      }
    })
  }
  // 分页列表
  list(pageNum?, pageSize?) {
    let that = this;
    this.isCheckedAll = false;
    this.getBody.nBatchno = _.trim(this.getBody.nBatchno);
    this.getBody.sFundName = _.trim(this.getBody.sFundName);
    this.getBody.sBeginOperatorZh = _.trim(this.getBody.sBeginOperatorZh);
    this.getBody.sCommitOperatorZh = _.trim(this.getBody.sCommitOperatorZh);
    this.getBody.sReceiverZh = _.trim(this.getBody.sReceiverZh);
    this.getBody.sMsgTitle = _.trim(this.getBody.sMsgTitle);
    this.getBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    this.getBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    this.modifyRemindPageService.list(this.getBody).subscribe(data => {
      if (data) {
        that.dataList = data.list;
        that.listPageInfo.currentPageNum = data.pageNum;
        that.listPageInfo.totalPages = data.pages;
        that.listPageInfo.total = data.total;
        that.listPageInfo.startRow = data.startRow;
        that.listPageInfo.endRow = data.endRow;
        window['$']('#remindQuery').modal('hide');
      }
    })
  }
  // 分页
  sizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      this.list();
    }
  }
  // 分页
  pageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    this.list(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }
  // 列表全选(所有列表公用)
  checkedAll() {
    if (this.isCheckedAll) {
      _.forEach(this.dataList, item => {
        item.isChecked = true;
      });
    } else {
      _.forEach(this.dataList, item => {
        item.isChecked = false;
      });
    }
  }
  // 判断列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.dataList, item => {
      if (item.isChecked) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.dataList.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  // 刷新列表
  refresh() {
    this.resetSearch();
    this.list();
  }
  // 显示模版
  showModel(type) {
    let that = this;
    let checkedItem = [];
    _.forEach(this.dataList, item => {
      if (item.isChecked) {
        checkedItem.push(item);
      }
    });
    if (checkedItem.length == 1) {
      switch (type) {
        case 'detail':
          this.showDetail(checkedItem[0]);
          break;
      }
    } else if (checkedItem.length < 1) {
      window['swal']("提示", "请选择一条记录!", "warning");
    } else if (checkedItem.length > 1) {
      window['swal']("提示", "只能选择一条记录!", "warning");
    }
  }
  // 打开搜索模态框
  showRemindQuery() {
    this.resetSearch();
    window['$']('#remindQuery').modal('show');
  }
  // 查看明细模版
  showDetail(item) {
    if (this.detailComponent && this.detailComponent.instance) {
      this.detailComponent.destroy();
    }
    const detailComponent = this.resolver.resolveComponentFactory(DetailComponent);
    this.detailComponent = this.detail.createComponent(detailComponent);
    this.detailComponent.instance.item = item;
    window['$']('#detail').modal('show');
  }
  // 接收者列表
  showRemind() {
    if (this.remindComponent && this.remindComponent.instance) {
      this.remindComponent.destroy();
    }
    const remindComponent = this.resolver.resolveComponentFactory(RemindComponent);
    this.remindComponent = this.modifyTargetRemind.createComponent(remindComponent);
    window['$']('#modifyTargetRemind').modal('show');
  }
  // 重置查询
  resetSearch() {
    this.getBody.pageIndex = 1;
    this.getBody.pageSize = 10;
    this.getBody.sOprType = '3';
    this.getBody.nBatchno = '';
    this.getBody.sSendFlag = 'N';
    this.getBody.sFundType = '';
    this.getBody.sFundName = '';
    this.getBody.sBeginOperatorZh = '';
    this.getBody.sCommitOperatorZh = '';
    this.getBody.sReceiverZh = '';
    this.getBody.sMsgTitle = '';
  }
  // 提醒
  remind() {
    let that = this;
    let checkedName = [];
    _.forEach(this.dataList, item => {
      if (item.isChecked) {
        checkedName.push(item.sFundName);
      }
    });
    let checkedNames = checkedName.join("、");
    if (checkedName.length == 0) {
      window['swal']("提示", "请选择一条或多条记录!", "warning");
    } else {
      this.resetRemind();
      this.defaultValue();
      this.remindBody.sSMSContent = "您好：以下投资范围指标已更新[ " + checkedNames + " ]投资范围表变更，请基金经理注意查阅";
      this.remindBody.sEmailContent =
        "您好：\n" +
        "投资范围变更信息如下：\n" +
        "账户名称1 { 变更字段1 [ 变更前 ： 变更后 ] }";
      window['$']('#remindInfo').modal('show');
    }
  }
  // 清空提醒模版
  resetRemind() {
    this.remindBody.auditOpr = '';
    this.auditOprZh = '';
    this.remindBody.auditOpr = '';
    this.remindBody.title = '';
    this.remindBody.sSMSContent = '';
    this.remindBody.sEmailContent = '';
    this.remindBody.content = '';
    this.remindBody.remark = '';
    this.remindBody.sSendFlag = '';
    this.remindBody.sButtonId = '';
  }
  // 提醒
  sendRemind() {
    let that = this;
    let checkedItem = [];
    _.forEach(this.dataList, item => {
      if (item.isChecked) {
        let it: any = {};
        it['sSendFlag'] = item.sSendFlag;
        it['nBatchno'] = item.nBatchno;
        it['sCommitOperator'] = item.sCommitOperator;
        it['sShTime'] = item.sShTime;
        it['sShDate'] = item.sShDate;
        it['sOprType'] = '3';
        it['sBeginOperator'] = item.sBeginOperator;
        it['nLastMsgBatchno'] = item.nLastMsgBatchno;
        it['sLastSendTime'] = item.sLastSendTime;
        it['sLastSendDate'] = item.sLastSendDate;
        checkedItem.push(it);
      }
    });
    let postBody: any = {
      auditContentBean: this.remindBody,
      pmsSendHisList: checkedItem
    }
    window['swal']({
      type: "warning",
      showCancelButton: true,
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      closeOnConfirm: false,
      showLoaderOnConfirm: true,
      title: "提示",
      text: "是否确认保存?",
      html: true
    }, function (isConfirm) {
      if (isConfirm) {
        console.log(postBody)
        delete postBody.auditContentBean.auditOprZh;
        that.modifyRemindPageService.sendRemind(postBody).subscribe(data => {
          if (data) {
            window['$']('#remindInfo').modal('hide');
            window['swal']("成功", "提醒信息已发送", "success");
            that.list();
          }
        })
      }
    })

  }

  //获取默认模板接口
  defaultValue() {
    let that = this;
    let getBody: any = {
      "sButtonId": '70132@invest_scope_data_btn_i_commit'
    }
    this.modifyRemindPageService.defaultValue(getBody).subscribe(data => {
      if (data) {
        console.log(data);
        if (Array.isArray(data)) {
          if (data.length > 1) {
            that.auditOprZh = data[0].sContentZh;
            that.remindBody.auditOpr = data[0].sContent;
            if (data[0].sSMSFlag == 'true') {
              that.sSMSFlag = true;
            }
            if (data[0].sEmailFlag == 'true') {
              that.sEmailFlag = true;
            }
            // that.remindBody.sSMSContent = data[1].sContent;
            // that.remindBody.sEmailContent = data[1].sContent;
            that.remindBody.title = data[1].sRemindTitle;
          }
        }
      }
    })
  }
  //设置默认接口
  setDefault() {
    let that = this;
    let postBody = _.cloneDeep(this.remindBody);
    postBody['sButtonId'] = '70132@invest_scope_data_btn_i_commit';
    postBody['sEmailFlag'] = _.cloneDeep(this.sEmailFlag);
    postBody['sEmailContent'] = _.cloneDeep(postBody.sSMSContent);
    postBody['sSMSFlag'] = _.cloneDeep(this.sSMSFlag);
    postBody['sSMSContent'] = _.cloneDeep(postBody.sEmailContent);
    delete postBody.content;
    if (postBody.sEmailFlag) {
      postBody.sEmailFlag = 'Y'
    } else {
      postBody.sEmailFlag = 'N'
    }
    if (postBody.sSMSFlag) {
      postBody.sSMSFlag = 'Y'
    } else {
      postBody.sSMSFlag = 'N'
    }
    console.log(postBody)
    window['swal']({
      type: "warning",
      showCancelButton: true,
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      closeOnConfirm: false,
      showLoaderOnConfirm: true,
      title: "提示",
      text: "<div style='max-height: 200px;overflow-y: auto;'>" + "请确认是否设置默认" + "</div>",
      html: true
    },
      function (isConfirm) {
        if (isConfirm) {
          that.modifyRemindPageService.setDefault(postBody).subscribe(data => {
            if (data) {
              window['swal']("提示", "设置默认成功", "success");
            }

          })
        }
      });
    console.log(postBody)
  }
}
